package com.zcl.IO.exchangeStream转换流;

import org.junit.Test;

import java.io.*;

/**
 * @Description:
 * @author: zcl
 * @date: 2022/3/15  14:04
 * 处理流二: 转换流: 属于字符流
 * InputStreamReaderTest: 将一个字节的输入流转换成字符的输入流
 * OutputStreamWriter: 将一个字符的输出流转换成字节的输出流
 * <p>
 * 作用: 提供字节流和字符流之间的转换
 */
public class InputStreamReaderTest {

    @Test
    public void inputStreamReaderTest() {
        FileInputStream fis = null;
        InputStreamReader isr = null;
        try {
            fis = new FileInputStream("src\\com\\zcl\\IO\\exchangeStream转换流\\writer.txt");
            //参数2指明了字符集,具体使用那种字符集,取决于改文件保存的时候采用的编码格式
            isr = new InputStreamReader(fis, "UTF-8");
            char[] cbuf = new char[10];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                String s = new String(cbuf, 0, len);
                System.out.println(s);
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test2() {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            FileInputStream fis = new FileInputStream("src\\com\\zcl\\IO\\exchangeStream转换流\\writer.txt");
            FileOutputStream fos = new FileOutputStream("src\\com\\zcl\\IO\\exchangeStream转换流\\writer_GBK.txt");

            isr = new InputStreamReader(fis, "utf-8");
            osw = new OutputStreamWriter(fos, "gbk");

            char[] cbuf = new char[20];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                osw.write(cbuf, 0, len);
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }
}
